﻿#include "as_memory.h"
#include <iostream>
#ifdef _WIN32
#include <windows.h>
#include <psapi.h>
#else
#include <stdio.h>
#include <cstring>
#endif

as::tools::MemoryLog::MemoryLog()
{
#ifdef _WIN32
	PROCESS_MEMORY_COUNTERS pmc;
	if (GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc)))
	{
		beg_ = pmc.WorkingSetSize;
	}
#else
	FILE *fp = fopen("/proc/self/status", "r");
	char line[128];
	while (fgets(line, 128, fp) != NULL)
	{
		if (strncmp(line, "VmRSS:", 6) == 0)
		{
			beg_ = atoi(line + 6);
			break;
		}
	}
	fclose(fp);
#endif

}

as::tools::MemoryLog::MemoryLog(std::function<void(size_t, size_t)> cb)
	:MemoryLog()
{
	cb_ = cb;
}

as::tools::MemoryLog::~MemoryLog()
{
	Tick();
}

void as::tools::MemoryLog::Tick()
{
	size_t end_ = 0;
#ifdef _WIN32
	PROCESS_MEMORY_COUNTERS pmc;
	if (GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc)))
	{
		end_ = pmc.WorkingSetSize;
	}
#else
	FILE *fp = fopen("/proc/self/status", "r");
	char line[128];
	while (fgets(line, 128, fp) != NULL)
	{
		if (strncmp(line, "VmRSS:", 6) == 0)
		{
			end_ = atoi(line + 6);
			break;
		}
	}
	fclose(fp);
#endif

	if (cb_)
	{
		cb_(beg_, end_);
	}
	else
	{
		std::cout << "before memory size:" << beg_ << " after size:" << end_ << " dif size:" << (double)(end_ - beg_) / 1024.0 / 1024.0 << "MB";
	}

	beg_ = end_;
}
